package ncme.auto.framework.core.services.utils;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import ncme.auto.framework.core.mapper.BaseMapperPlus;
import org.springframework.beans.factory.annotation.Autowired;

import java.lang.reflect.Field;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

public class MyBatisHelper<E> {

    @Autowired
    private BaseMapperPlus<E> mapper;

    private final Class<?> eType = getParaType();

    public List<Integer> selectIntSingleField(String fieldName) throws Throwable{
        QueryWrapper<E> wrapper = new QueryWrapper<>();
        wrapper.select("DISTINCT "+fieldName);
        List<E> results = mapper.selectList(wrapper);
        List<Integer> res = new ArrayList<>();

        Field declaredField = eType.getDeclaredField(fieldName);
        declaredField.setAccessible(true);
        for (E e :results){
            res.add(declaredField.getInt(e));
        }
        return res;
    }

    public List<String> selectStrSingleField(String fieldName)throws Throwable{
        QueryWrapper<E> wrapper = new QueryWrapper<>();
        wrapper.select("DISTINCT "+fieldName);
        List<E> results = mapper.selectList(wrapper);
        List<String> res = new ArrayList<>();

        Field declaredField = eType.getDeclaredField(fieldName);
        declaredField.setAccessible(true);
        for (E e :results){
            res.add(declaredField.get(e).toString());
        }
        return res;
    }

    private Class<?> getParaType(){
        Type type = getClass().getGenericSuperclass();
        ParameterizedType parameterizedType_This = (ParameterizedType) type;
        Type entityType = parameterizedType_This.getActualTypeArguments()[0];
        return (Class<?>) entityType;
    }
}
